<template>
    <div class="app-container">

        <div :class="['filter-container',{'open':formState}]">
            <a v-if="screenState" class="form-more" href="#" title="更多筛选" @click="formState = !formState"><i
                    :class="formState ? 'el-icon-caret-top':'el-icon-caret-bottom'" /></a>
            <!-- <el-form ref="form" :model="form" @keyup.enter.native="handleFilter()" label-width="80px"> -->

            <!-- 筛选框需要些双份 一种是没有展开状态下的  只有主要的几个筛选框，另一种是全部的筛选框都展示 也就是展开状态下的 -->
            <!-- 没有展开状态下的筛选框 -->
            <el-form v-if="!formState" ref="filtrateForm" :inline="true" :model="filtrateForm" label-width="80px">
                <el-form-item label="园区名称:">
                    <el-select v-model="filtrateForm.parkId" placeholder="请选择" @change="park_change">
                        <el-option v-for="item in park_options" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="客户类型:">
                    <!-- <el-input v-model.trim="filtrateForm.name" placeholder="请输入" style="width:160px;" clearable /> -->
                    <el-select v-model="filtrateForm.customerType" placeholder="请选择" @change="park_change">
                        <el-option v-for="item in customer_type_option" :key="item.value" :label="item.lable" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="客户状态:">
                    <!-- <el-input v-model.trim="filtrateForm.name" placeholder="请输入" style="width:160px;" clearable /> -->
                    <el-select v-model="filtrateForm.state" placeholder="请选择" @change="park_change">
                        <el-option v-for="item in customer_state_option" :key="item.value" :label="item.lable" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <!-- <el-form-item label="姓名/手机:">
                    <el-input v-model.trim="filtrateForm.customInfo" placeholder="请输入" style="width:160px;" clearable />
                </el-form-item> -->

                <el-form-item>
                    <el-button @click="getList()">查询</el-button>
                    <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                        @click="handleCreate()">新增</el-button>
                    <!-- <el-button v-permission="['sys:config:delete']" type="danger" :disabled="dataListSelections.length <= 0"
                        @click="deleteHandle()">批量删除</el-button> -->
                    <el-button :loading="downloadLoading1" style="margin-left: 10px;" class="filter-item" type="primary"
                        @click="handleDownloadMock">
                        下载模板
                    </el-button>
                    <el-upload class="upload-demo" style="margin-left: 10px;" :headers="headers" :show-file-list="false" :action="action"
                        :on-success="handleSuccess" multiple :limit="1" name="file">
                        <el-button type="primary">导入</el-button>
                    </el-upload>
                    <el-button :loading="downloadLoading" style="margin-left: 10px;" class="filter-item" type="primary"
                        @click="handleDownload">
                        导出
                    </el-button>
                </el-form-item>
            </el-form>

            <!-- 展开状态下的筛选框 -->
            <el-form v-if="formState" ref="form" :inline="true" :model="filtrateForm" label-width="80px">
                <el-form-item label="园区名称:">
                    <el-select v-model="filtrateForm.parkId" placeholder="请选择" @change="park_change">
                        <el-option v-for="item in park_options" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="客户类型:">
                    <!-- <el-input v-model.trim="filtrateForm.name" placeholder="请输入" style="width:160px;" clearable /> -->
                    <el-select v-model="filtrateForm.customerType" placeholder="请选择" @change="park_change">
                        <el-option v-for="item in customer_type_option" :key="item.value" :label="item.lable" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="客户状态:">
                    <!-- <el-input v-model.trim="filtrateForm.name" placeholder="请输入" style="width:160px;" clearable /> -->
                    <el-select v-model="filtrateForm.state" placeholder="请选择" @change="park_change">
                        <el-option v-for="item in customer_state_option" :key="item.value" :label="item.lable" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="姓名/手机:">
                    <el-input v-model.trim="filtrateForm.customInfo" placeholder="请输入" style="width:160px;" clearable />
                </el-form-item>

            </el-form>
            <div v-if="formState" class="filter-button">
                <el-button @click="getList()">查询</el-button>
                <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                    @click="handleCreate()">新增</el-button>
                <!-- <el-button v-permission="['sys:config:delete']" type="danger" :disabled="dataListSelections.length <= 0"
                        @click="deleteHandle()">批量删除</el-button> -->
                <el-upload class="upload-demo" style="margin-left: 10px;" :headers="headers" :show-file-list="false" :action="action"
                    :on-success="handleSuccess" multiple :limit="1" name="file">
                    <el-button type="primary">导入</el-button>
                </el-upload>
                <el-button :loading="downloadLoading" style="margin-left: 10px;" class="filter-item" type="primary" @click="handleDownload">
                    导出
                </el-button>
            </div>

        </div>

        <!-- <div :class="['filter-container']"> -->

        <!-- 筛选框需要些双份 一种是没有展开状态下的  只有主要的几个筛选框，另一种是全部的筛选框都展示 也就是展开状态下的 -->
        <!-- 没有展开状态下的筛选框 -->
        <!-- <el-form ref="filtrateForm" :inline="true" :model="filtrateForm" label-width="80px">
                <el-form-item label="园区名称:">
                    <el-select v-model="filtrateForm.parkId" placeholder="请选择" @change="park_change">
                        <el-option v-for="item in park_options" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="客户类型:">
                     <el-input v-model.trim="filtrateForm.name" placeholder="请输入" style="width:160px;" clearable /> 
                    <el-select v-model="filtrateForm.customerType" placeholder="请选择" @change="park_change">
                        <el-option v-for="item in customer_type_option" :key="item.value" :label="item.lable" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="客户状态:">
                    <el-select v-model="filtrateForm.state" placeholder="请选择" @change="park_change">
                        <el-option v-for="item in customer_state_option" :key="item.value" :label="item.lable" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="姓名/手机:">
                    <el-input v-model.trim="filtrateForm.customInfo" placeholder="请输入" style="width:160px;" clearable />
                </el-form-item>

                <el-form-item>
                    <el-button @click="getList()">查询</el-button>
                    <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                        @click="handleCreate()">新增</el-button>
                    <el-upload class="upload-demo" style="margin-left: 10px;" :headers="headers" :show-file-list="false" :action="action"
                        :on-success="handleSuccess" multiple :limit="1" name="uploadFile">
                        <el-button type="primary">批量导入</el-button>
                    </el-upload>
                    <el-button :loading="downloadLoading" style="margin-left: 10px;" class="filter-item" type="primary"
                        @click="handleDownload">
                        导出
                    </el-button>
                </el-form-item>

            </el-form> -->

        <!-- </div> -->

        <div :class="['table',{'open':formState}]">
            <div class="table-container">
                <el-table :key="tableKey" v-loading="listLoading" row-key="menuId" height="100%" :data="list" border fit
                    highlight-current-row style="width: 100%;" @selection-change="selectionChangeHandle">

                    <el-table-column type="selection" header-align="center" align="center" width="50" />

                    <el-table-column prop="parkName" header-align="center" align="center" label="园区名称" />
                    <el-table-column prop="customerName" header-align="center" align="center" label="客户姓名" />
                    <el-table-column prop="type" header-align="center" align="center" label="类型">
                        <template slot-scope="scope">{{ scope.row.type | customerTypeFilter }}</template>
                    </el-table-column>
                    <el-table-column prop="mobile" header-align="center" align="center" label="手机号" />
                    <el-table-column prop="state" header-align="center" align="center" label="状态">
                        <template slot-scope="scope">{{ scope.row.state | customerStateFilter }}</template>
                    </el-table-column>
                    <el-table-column prop="houseAmounts" header-align="center" align="center" label="房屋数量" />
                    <el-table-column prop="updateTime" header-align="center" align="center" width="180" label="最后编辑时间">
                        <template slot-scope="scope">{{ scope.row.updateTime | toData }}</template>
                    </el-table-column>
                    <el-table-column prop="updateUserName" header-align="center" align="center" label="编辑人" />
                    <el-table-column header-align="center" align="center" width="150" label="操作">
                        <template slot-scope="scope">
                            <el-button v-permission="['sys:config:update']" type="text" size="small" @click="handleUpdate(scope.row)">
                                修改
                            </el-button>
                            <el-button v-permission="['sys:config:delete']" type="text" size="small" @click="deleteHandle(scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>

                </el-table>
            </div>
        </div>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        <!-- //新增或者修改弹框 -->
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @getList="handleFilter" />

    </div>
</template>

<script>
import { getCustomerList, daleteCustomer, getParkListAll } from '@/api/assets'// 请求数据
import { customerExportExcel, downloadMock, customerImportExcel } from '@/api/index'// 请求数据
import { customerType, customerState } from '@/utils/enum'
import permission from '@/directive/permission/index.js' // 权限判断指令
import checkPermission from '@/utils/permission' // 权限判断函数
import { toDate } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination 分页组件
import AddOrUpdate from './add-or-update' // 新增或者修改弹框

export default {
    name: 'LayoutTable',
    components: { Pagination, AddOrUpdate },
    directives: { permission }, // 指令
    // 过滤
    filters: {
        toData (data) {
            return toDate(data)
        },
        customerTypeFilter (e) {
            let map = customerType;
            return map[e]
        },
        customerStateFilter (e) {
            let map = customerState;
            return map[e]
        }
    },
    data () {
        return {
            screenState: true, // 筛选框是否展示下拉按钮
            formState: false, // 筛选框的 开合
            // 筛选框的 form 表单
            filtrateForm: {
                parkId: '',
                customerType: '',
                state: '',
                customInfo: ''
            },
            // 表单验证
            rules: {
            },
            dataListSelections: [], // 批量删除选中
            tableKey: 0,
            listLoading: true, // 表格加载数据时的 loading
            list: [], // 表格数据
            total: 0, // 总条数
            listQuery: { // 表格当前页 和 当前页的展示数量
                page: 1,
                limit: 20
            },
            addOrUpdateVisible: false,// 新增和修改 弹框展示隐藏
            park_options: [],
            downloadLoading: false, // 导出按钮 的 loading
            downloadLoading1: false, // 下载模板 的 loading
            action: customerImportExcel(),//导入地址
            headers: {},//导入参数
        }
    },
    computed: {
        customer_type_option () {
            let arr = [{ lable: '全部', value: '' }]
            for (let key in customerType) {
                arr.push({
                    lable: customerType[key],
                    value: key
                })
            }
            return arr
        },
        customer_state_option () {
            let arr = [{ lable: '全部', value: '' }]
            for (let key in customerState) {
                arr.push({
                    lable: customerState[key],
                    value: key
                })
            }
            return arr
        }
    },
    created () {
        this.getPark()
        this.getList()
    },
    methods: {
        async getPark () {
            const res = await getParkListAll().catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            this.park_options = [{ name: '全部', id: '' }].concat(data)
            console.log(data)
        },
        // 获取表格数据
        async getList () {
            this.listLoading = true
            // 筛选+分页
            const params = Object.assign({
                parkId: this.filtrateForm.parkId,
                customerType: this.filtrateForm.customerType,
                state: this.filtrateForm.state,
                customInfo: this.filtrateForm.customInfo
            }, this.listQuery)
            // 请求
            const res = await getCustomerList(params).catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            console.log(data)
            // data.list.forEach(item => {
            //     item.detailAddress = `${item.province}/${item.city}/${item.county}`
            //     if (!item.allHouses) {
            //         item.rentedOrAll = '--'
            //         return
            //     }
            //     item.rentedOrAll = Math.round(item.allHouses / item.rentedHouses * 100) + '%'
            // })
            this.list = data.list
            this.total = data.totalCount
            this.listLoading = false
        },
        // 重新获取表格数据 页码归为1
        handleFilter () {
            this.listQuery.page = 1
            this.getList()
        },
        // 新增数据 -- 打开弹框
        handleCreate () {
            this.addOrUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init('create')
            })
        },
        // 修改数据 -- 打开弹框
        handleUpdate (row) {
            this.addOrUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init('update', row)
            })
        },
        // 批量删除数据 - 多选
        selectionChangeHandle (val) {
            this.dataListSelections = val
        },
        // 删除数据 批量删除的话 不用传参
        deleteHandle (data) {
            const idS = data ? [data.id] : this.dataListSelections.map(item => { return item.id })
            const nameS = data ? [data.customerName] : this.dataListSelections.map(item => { return item.customerName })
            this.$confirm(`确定对[${nameS.join('、')}]进行[删除]操作?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 提交删除
                const { code, message } = await daleteCustomer({}, idS)
                // 成功
                this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                        this.handleFilter()// 刷新数据
                    }
                })
            })
        },


        // ---->>>>
        park_change (e) {
            console.log(e)
        },
        //导入成功
        handleSuccess (data, file, fileList) {
            if (data && data.code === 200) {
                this.$message({
                    message: "操作成功",
                    type: "success",
                    duration: 1500,
                    onClose: () => {
                        this.handleFilter()// 刷新数据
                    }
                });
            } else {
                this.$message.error(data.message);
            }
        },
        //下载模板
        handleDownloadMock () {
            this.downloadLoading1 = true
            // let params = `?&page=${this.listQuery.page}&limit=${this.listQuery.limit}`
            // const url = `${process.env.VUE_APP_BASE_API}/assets/house/exportExcel${params}`
            const url = downloadMock('个人客户导入模板.xlsx')
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            // link.setAttribute('download', 'xxx.xlsx');
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            setTimeout(() => {
                this.dw()
            }, 2000)
        },
        dw () {
            const url1 = downloadMock('公司客户导入模板.xls')
            const link1 = document.createElement('a')
            link1.style.display = 'none'
            link1.href = url1
            document.body.appendChild(link1)
            link1.click()
            document.body.removeChild(link1)

            this.downloadLoading1 = false
        },
        //导出 后台接口
        handleDownload () {
            this.downloadLoading = true
            // let params = `?&page=${this.listQuery.page}&limit=${this.listQuery.limit}`
            // const url = `${process.env.VUE_APP_BASE_API}/assets/house/exportExcel${params}`
            const url = customerExportExcel(this.listQuery)
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            // link.setAttribute('download', 'xxx.xlsx');
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            this.downloadLoading = false
        },

    }
}
</script>
<style lang="scss" scoped>
//表格布局的注释：
//$rowLength 这个变量表示了 筛选的搜索框会有多少行，由于在不同宽度显示器下 所占行数会不一定 ，所以下面使用媒体查询 做兼容
//最小兼容至 1366
@import '~@/styles/layout-table.scss';
$rowLength: 2;
@media all and (min-width: 1659px) {
    $rowLength: 1;
    @include calculation($rowLength: $rowLength);
}
@media all and (max-width: 1659px) {
    $rowLength: 1;
    @include calculation($rowLength: $rowLength);
}
</style>
